<template>
	<view style="height: 100%;">
		<!-- 遮罩层 -->
		<view class="mask pay-actionsheet-mask" :class="[show?'pay-mask-show':'']"></view>
		<!-- 组件内容 -->
		<view class="bg-light fixed-bottom pay-actionsheet" :class="[show?'pay-actionsheet-show':'']">
			<view class="h2 text-muted" style="position: absolute;top: 0; right: 20rpx;" @tap="handleClose()">×</view>
			<view class="font-weight-bold text-center pt-5">
				<text class="font-lg">￥</text><text class="h2">{{amount}}</text>
			</view>
			<view class="text-center pb-5">
				<text class="font">待支付</text>
			</view>
			<view class="text-center py-5">
				<text class="font-lg font-weight-bold">请选择支付方式</text>
			</view>
			<!-- 支付方式 -->
			<radio-group class="pt-3" @change="select">
				<label v-for="(item,index) in way" :key="index" style="position: relative;"
					class="mx-4 mt-2 bg-white p-3 flex align-center rounded-lg">
					<image :src="Domain_ICON + item.icon" class="rounded" style="width: 35rpx;height: 35rpx;" mode=""></image>
					<text class="font-md ml-2 font-weight-bold">{{item.value}}</text>
					<radio :value="item.value" style="transform:scale(0.7); position: absolute; right: 20rpx;" :checked="item.select" />
				</label>
			</radio-group>
			<view class="px-4 py-2 fixed-bottom ">
				<view class="bg-info rounded text-center py-3 text-white font-weight-bold font" @click="submit()"
					hover-class="bg-hover-info" :hover-stay-time="150">{{payway}}￥{{amount}}</view>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp()
	export default {
		data() {
			return {
				loading: false ,//节流
				times:'',
				payway:'微信支付',//支付方式
				balance:'',//用户余额
				collection: {
					Collection_SerialNumber: "",
					Store_SerialNumber: '',
					Sales_Order_SerialNumber: "",
					Collection_Date: '',
					Collection_Amount: 0,
					Sales_Amount: 0,
					Change_Amount: 0,
					Order_Type: 1,
					App_ID: app.globalData.appid,
					Open_ID: app.globalData.openid,
					Enterprise_Info_SerialNumber: app.globalData.enterprise,
					Children: {
						collection_detail: []
					}
				},
				Domain_ICON: app.globalData.Domain_ICON, //全局变量域名
			}
		},
		props: {
			show: { //显示支付方式
				type: Boolean,
				default: false
			},
			amount: { //总计金额
				type: null,
				default: ""
			},
			sales_orders: { //总计金额
				type: Array,
				default: function() {
					return []
				}
			},
			Article_Name:{
				type:Array,
				default:[]
			},
			way: { //支付方式
				type: Array,
				default: function() {
					return [{
						icon: '/static/icon/WXlogo.png',
						value: '微信支付',
						select: true
					}
					// ,{
					// 	icon: '/static/icon/Balancepay.png',
					// 	value: '余额支付',
					// 	select: false
					// },
					]
				}
			},
		},
		methods: {
			handleClose() { //关闭
				this.$emit('Close');
			},
			//选中的支付方式
			select(e){
				this.payway = e.detail.value
			},
			getData(Sales_Order_SerialNumber){ //查询余额
				uni.request({
					url:app.globalData.Domain_Name+"/WXMemberAccountInfoIDAction",
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "POST",
					data: {
						Member_SerialNumber: app.globalData.memberInfo.Member_SerialNumber,
					},
					success: (res) => {
						this.balance = this.accAdd(res.data[0].Prepayment_Balance,res.data[0].Gift_Balance)
					    //判断余额是否大于销售价格
						if(this.balance>=this.amount){
							uni.request({//
								header: {
									'Content-Type': 'application/x-www-form-urlencoded'
								},
								url: app.globalData.Domain_Name + '/WXWeChatDefrayAction',
								method: "POST",
								data: {
									Sales_Order_SerialNumber,
									Collection_Type:"储值账户",
								},
								success: (res) => {
									console.log(res.data)
									uni.hideLoading()
									if(res.data.Status=='success'){
										uni.showToast({
											title:'余额支付成功',
											icon:'success'
										})
									}else{
										uni.showToast({
											title:'系统繁忙稍后重试',
											icon:'fail'
										})
									}
								},
							})
						}else{
							uni.request({//
								header: {
									'Content-Type': 'application/x-www-form-urlencoded'
								},
								url: app.globalData.Domain_Name + '/WXWeChatDefrayAction',
								method: "POST",
								data: {
									Data: JSON.stringify({
										WeChatPay:this.accAdd(this.amount,-this.balance),
										BalancePay:this.balance
									}),
									Sales_Order_SerialNumber,
									Collection_Type:"储值账户+微信支付"
								},
								success: (res) => {
									var _this = this
									let appId = res.data.sdk_appid;
									let timeStamp = res.data.sdk_timestamp+'';
									let nonceStr = res.data.sdk_noncestr;
									let packageX = res.data.sdk_package;
									let signType = res.data.sdk_signtype;
									let paySign = res.data.sdk_paysign;
									console.log(res.data);
									if (res.data.result_msg == "SUCCESS") {
										uni.hideLoading();
										uni.requestPayment({
											provider: 'wxpay',
											appId: appId,
											timeStamp: timeStamp,
											nonceStr: nonceStr,
											package: packageX,
											signType: signType,
											paySign: paySign,
											success: function(res) {
												uni.showToast({
													title: '支付成功！',
													icon: 'success',
													success() {
														uni.navigateTo({
															url:`/pages/paycomplete/paycomplete?price=${_this.amount}`
														})
													}
												})
											},
											fail: function(err) {
												console.log(err);
												uni.showToast({
													title: '已取消！',
													icon: 'error'
												})
											},
											//调起支付后打开懒加载
											complete: () => {
												this.loading = false
												uni.hideLoading();
											}
										})
									} else {
										this.loading = false
										uni.hideLoading();
										uni.showToast({
											title: '提交失败，请重试！',
											icon: 'error'
										})
									}
								},
							})
						}
					}
				})
			},
			submit() { //校验库存
			console.log(2)
				let that = this
				if (!this.loading) {
					this.loading = true
					uni.showLoading({
						title: '提交中...',
					});
					let arr = []
					this.sales_orders.forEach(item=>{
						arr.push({
							Sales_Unit_Price_Stock_SerialNumber:item.Sales_Unit_Price_Stock_SerialNumber,
							Quantity:item.Quantity
						})
					})
					console.log(this.Article_Name);
					uni.request({
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						url: app.globalData.Domain_Name + '/WX2CheckStockAction',
						method: "POST",
						data: {
							Data: JSON.stringify(arr)
						},
						success: (res) => {
							if (res.data.Status == 'success') {
								this.defray()
							} else if (res.data.Status == 'insufficient') {
								this.loading = false
								uni.hideLoading();
								uni.showToast({
									title: '库存不足!',
									icon: 'error'
								})
							} else {
								this.loading = false
								uni.hideLoading();
								uni.showToast({
									title: '提交失败，请重试！',
									icon: 'error'
								})
							}
						},
					})
				}
			},
			defray() { //调起支付
				let year = new Date().getFullYear();
				let month = new Date().getMonth() + 1;
				let days = new Date().getDate();
				if (month < 10) {
					month = '0' + month
				}
				if (days < 10) {
					days = '0' + days
				}
				const that = this
				uni.request({ //提交订单
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					url: app.globalData.Domain_Name + '/WXShopCarTotalOrders',
					method: "POST",
					data: {
						Data: JSON.stringify(that.sales_orders),
					},
					success: (res) => {
						console.log(res)
						if(this.payway=='余额支付'){
							this.getData(res.data.Data)
						}else{
							this.sales_orders.forEach(item=>{
								this.collection.Sales_Order_SerialNumber = item.Sales_Order_SerialNumber
								this.collection.Sales_Amount = this.accAdd(this.collection.Sales_Amount,item.Amount)
								this.collection.Store_SerialNumber = item.Store_SerialNumber
								this.collection.Children.collection_detail.push({
									Collection_Detail_SerialNumber: "",
									Collection_SerialNumber: "",
									Sales_Order_SerialNumber: item.Sales_Order_SerialNumber,
									Store_SerialNumber : item.Store_SerialNumber,
									Collection_Type: "微信支付",
									Collection_Related_Number: "",
									Amount: item.Amount,
									Gift_Type: 0,
									Gift_Amount: 0,
								})
							})
							that.time()
							if (res.data.Status == 'success') {
								uni.request({ //提交收款表
									header: {
										'Content-Type': 'application/x-www-form-urlencoded'
									},
									url: app.globalData.Domain_Name + '/WXAddAction',
									method: "POST",
									data: {
										Data: JSON.stringify({
											collection: [that.collection]
										}),
										Open_ID:app.globalData.openid
									},
									success: (res) => {
										if (res.data.Status == 'success') {
											that.pay(res.data, year+''+month+''+days+'')
										} else {
											that.loading = false
											uni.hideLoading();
											uni.showToast({
												title: '提交失败，请重试！',
												icon: 'error'
											})
										}
									},
								})
							} else {
								that.loading = false
								uni.hideLoading();
								uni.showToast({
									title: '提交失败，请重试！',
									icon: 'error'
								})
							}
						}

					},
				})
			},
			pay(data, time) {
				var _this = this
				uni.request({
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					url: app.globalData.Domain_Name + '/WXWeChatPayForMiniProgramsAction',
					method: "POST",
					data: {
							// zhifu: 'FWC',
							// openid: app.globalData.openid,
							// mchnt: "12149" + time + data.Data,
							Amount: this.accMul(this.collection.Sales_Amount, 100),
							// attach: '消费-微信支付',
							App_ID:app.globalData.appid,
							Article_Name:this.Article_Name[0]+'等...',
							Collection_SerialNumber:"12149" + time + data.Data,
							Open_ID:app.globalData.openid
					},
					success: (res) => {
						let appId = res.data.sdk_appid;
						let timeStamp = res.data.sdk_timestamp+'';
						let nonceStr = res.data.sdk_noncestr;
						let packageX = res.data.sdk_package;
						let signType = res.data.sdk_signtype;
						let paySign = res.data.sdk_paysign;
						console.log(res.data);
						if (res.data.result_msg == "SUCCESS") {
							uni.hideLoading();
							uni.requestPayment({
								provider: 'wxpay',
								appId: appId,
								timeStamp: timeStamp,
								nonceStr: nonceStr,
								package: packageX,
								signType: signType,
								paySign: paySign,
								success: function(res) {
									uni.showToast({
										title: '支付成功！',
										icon: 'success',
										success() {
											uni.navigateTo({
												url:`/pages/paycomplete/paycomplete?price=${_this.amount}`
											})
										}
									})
								},
								fail: function(err) {
									console.log(err)
									uni.showToast({
										title: '已取消！',
										icon: 'error'
									})
								},
								//调起支付后打开懒加载
								complete: () => {
									this.loading = false
									uni.hideLoading();
								}
							})
						} else {
							console.log('ha');
							this.loading = false
							uni.hideLoading();
							uni.showToast({
								title: '提交失败，请重试！',
								icon: 'error'
							})
						}
					},
				})
			},
			accMul(arg1, arg2) { //浮点型相乘
				let m = 0,
					s1 = arg1.toString(),
					s2 = arg2.toString();
				try {
					m += s1.split(".")[1].length
				} catch (e) {}
				try {
					m += s2.split(".")[1].length
				} catch (e) {}
				return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
			},
			accAdd(arg1, arg2) {	//浮点型相加
				var r1, r2, m;
				try {r1 = arg1.toString().split(".")[1].length} catch (e) {r1 = 0}
				try {r2 = arg2.toString().split(".")[1].length} catch (e) {r2 = 0}
				m = Math.pow(10, Math.max(r1, r2))
				return (arg1 * m + arg2 * m) / m
			},
			time(){
				let year = new Date().getFullYear();
				let month = new Date().getMonth() + 1;
				let days = new Date().getDate();
				let hour = new Date().getHours()
				let minutes = new Date().getMinutes()
				let second = new Date().getSeconds()
				if (month < 10) {
					month = '0' + month
				}
				if (days < 10) {
					days = '0' + days
				}
				if (hour < 10) {
					hour = '0' + hour
				}
				if (minutes < 10) {
					minutes = '0' + minutes
				}
				if (second < 10) {
					second  = '0' + second
				}
				this.collection.Collection_Date = year+'-'+month+'-'+days+' '+hour+':'+minutes+':'+second
			}
		},
		onLoad() {
			console.log(2)
		}
	}
</script>

<style lang="scss">
	.pay-actionsheet {
		width: 100%;
		height: 100%;
		visibility: hidden;
		transform: translate3d(0, 100%, 0);
		transform-origin: center;
		transition: all 0.3s ease-in-out;
	}

	.pay-actionsheet-show {
		transform: translate3d(0, 0, 0);
		visibility: visible;
	}

	.pay-actionsheet-mask {
		background: rgba(0, 0, 0, 0.6);
		transition: all 0.3s ease-in-out;
		opacity: 0;
		visibility: hidden;
	}

	.pay-mask-show {
		opacity: 1;
		visibility: visible;
	}
</style>